require([ "dojo/parser", "dojo/ready", "dijit/registry", "dojo/dom",
		"dojo/dom-form", "dojo/json", "dojo/_base/fx", "dojo/request",
		"dojo/on", "dijit/layout/BorderContainer", "dijit/layout/TabContainer",
		"dijit/layout/ContentPane", "dojo/domReady!" ], function(parser, ready,
		registry, dom, domForm, JSON, fx, request, on) {

	var roleSetting = {
		view : {
			addHoverDom : addHoverDom,
			removeHoverDom : removeHoverDom,
			selectedMulti : false,
			dblClickExpand : dblClickExpand
		},
		data : {
			simpleData : {
				enable : true,
				idKey : "id",
				pIdKey : "pid"
			}
		},
		callback : {
			onClick : bindForm
		}
	};

	function dblClickExpand(treeId, treeNode) {
		return treeNode.level > 0;
	}

	function addHoverDom(treeId, treeNode) {

		var _pid = treeNode.pid;
		var _id = treeNode.id;
		var sObj = $("#" + treeNode.tId + "_span");
		if ($("#addBtn_" + _id).length > 0 || $("#delBtn_" + _id).length > 0) {
			return;
		}
		var addRoleStr = "<span class='button addNode' id='addBtn_" + _id
				+ "' title=\"增加角色\" onfocus='this.blur();'></span>";
		var deleteRoleStr = "<span class='button deleteNode' id='delBtn_" + _id
				+ "' title=\"删除角色\" onfocus='this.blur();'></span>";
		var str = "";

		if ("root" == _id) {
			str = addRoleStr;
		} else {
			str = addRoleStr + deleteRoleStr;
		}
		sObj.after(str);

		var btnAdd = $("#addBtn_" + _id);
		if (btnAdd) {
			btnAdd.bind("click", function() {
				var _data = {
					pid : _id
				};
				request.post("add.action", {
					data : _data,
					handleAs : "json"
				}).then(function(response) {
					var zTree = $.fn.zTree.getZTreeObj("roleTree");
					zTree.addNodes(treeNode, response);
					var node = zTree.getNodeByParam("id", response.id);
					zTree.selectNode(node);
					clearForm();
					clickNode(node);
				}, function(error) {
					alert(error);
				});
			});
		}

		var btnDel = $("#delBtn_" + _id);
		if (btnDel) {
			btnDel.bind("click", function() {
				request.post("remove.action", {
					handleAs : "json",
					data : {
						id : _id
					}
				}).then(function(response) {
					var success = response.success;
					if ("1" == success) {
						var zTree = $.fn.zTree.getZTreeObj("roleTree");
						var node = zTree.getNodeByParam("id", _id);
						zTree.removeNode(node);
						clearForm();
					} else {
						alert("删除失败");
					}
				}, function(error) {
					alert(error);
				});
			});
		}
	}

	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_" + treeNode.id).unbind().remove();
		var delBtn = $("#delBtn_" + treeNode.id);
		if (delBtn) {
			delBtn.unbind().remove();
		}
	}

	function removeRole(treeId, treeNode) {
		var id = treeNode.id;
		request.post("remove.action", {
			handleAs : "json",
			data : {
				id : id
			}
		}).then(function(response) {
			var success = response.success;
			alert(success);
			if ("1" == success) {
				return true;
			} else {
				return false;
			}
		}, function(error) {
			return false;
			alert(error);
		});
	}

	function bindForm(event, treeId, treeNode, clickFlag) {
		registry.byId("name").set("value", treeNode.name);
		registry.byId("id").set("value", treeNode.id);
		registry.byId("pid").set("value", treeNode.pid);
		registry.byId("remark").set("value", treeNode.remark);
		registry.byId("userLimit").set("value", treeNode.userLimit);
		var tabs = registry.byId("infoTab");
		var basePane = registry.byId("basePane");
		tabs.selectChild(basePane);
		bindResourceTree(treeNode.id);
	}

	function clickNode(node) {
		registry.byId("name").set("value", node.name);
		registry.byId("id").set("value", node.id);
		registry.byId("pid").set("value", node.pid);
		registry.byId("remark").set("value", node.remark);
		registry.byId("userLimit").set("value", node.userLimit);
		var tabs = registry.byId("infoTab");
		var basePane = registry.byId("basePane");
		tabs.selectChild(basePane);
	}
	
	function clearForm() {
		registry.byId("name").set("value", "");
		registry.byId("id").set("value", "");
		registry.byId("pid").set("value", "");
		registry.byId("remark").set("value", "");
		registry.byId("userLimit").set("value", "");
	}
	
	function bindResourceTree(_roleId) {
		var zTree = $.fn.zTree.getZTreeObj("resourceTree");
		zTree.checkAllNodes(false);
		request.post("getRelatingResource.action", {
			handleAs : "json",
			data:{roleId:_roleId}
		}).then(function(_resourceCheckData) {
			if (_resourceCheckData) {
				for(var i =0; i<_resourceCheckData.length; i++) {
					var _node = zTree.getNodeByParam("id",  _resourceCheckData[i]);
					zTree.checkNode(_node, true, false);
				}
			}
		}, function(error) {
			alert(error);
		});		
	}

	var resourceSetting = {
		check : {
			chkboxType : {
				"Y" : "p",
				"N" : "ps"
			},
			enable : true
		},
		data : {
			simpleData : {
				enable : true,
				idKey : "id",
				pIdKey : "pid"
			}
		}
	};

	/**
	 * 构建角色树
	 */
	function buildRoleTree() {
		request.post("tree.action", {
			handleAs : "json"
		}).then(function(_roleTreeData) {
			$.fn.zTree.init($("#roleTree"), roleSetting, _roleTreeData);
		}, function(error) {
			alert(error);
		});
	}

	/**
	 * 构建资源树
	 */
	function buildResourceTree() {
		request.post("../resource/tree.action", {
			handleAs : "json"
		}).then(
				function(_resourceTreeData) {
					console.log(_resourceTreeData);
					$.fn.zTree.init($("#resourceTree"), resourceSetting,
							_resourceTreeData);
					var zTree = $.fn.zTree.getZTreeObj("resourceTree");
					var rootNode = zTree.getNodeByParam("id", "root");
					rootNode.nocheck = true;
					zTree.updateNode(rootNode);					
				}, function(error) {
					alert(error);
				});
	}

	parser.parse();
	ready(function() {
		buildRoleTree();
		buildResourceTree();

		var btnSaveRole = registry.byId("btnSave");
		btnSaveRole.on("click", function(evt) {
			var formData = domForm.toJson("roleForm");
			var formDataObject = JSON.parse(formData);
			request.post("modify.action", {
				handleAs : "json",
				data : formDataObject
			}).then(function(response) {
				alert(response.success);
				var zTree = $.fn.zTree.getZTreeObj("roleTree");
				var node = zTree.getNodeByParam("id", formDataObject.id);
				for ( var key in formDataObject) {
					node[key] = formDataObject[key];
				}
				zTree.updateNode(node);
			}, function(error) {
				alert(error);
			});

		});

		var btnObjRelatingResource = registry.byId("btnRelatingResource");
		btnObjRelatingResource.on("click", function(evt) {
			var roleTreeObj = $.fn.zTree.getZTreeObj("roleTree");
			var roles = roleTreeObj.getSelectedNodes();
			if (roles && roles.length > 0) {
				
				var _roleId = roles[0].id;
				
				var zTree = $.fn.zTree.getZTreeObj("resourceTree");
				var nodes = zTree.getCheckedNodes(true);
				if (nodes && nodes.length > 0) {
					var resourceArray = new Array();
					for ( var i = 0; i < nodes.length; i++) {
						resourceArray.push(nodes[i].id);
					}
					
					var _data = {
							roleId : _roleId,
							resourceIdList : resourceArray
					};
					
					request.post("relating.action", {
						handleAs : "json",
						data : _data
					}).then(function(response) {
						
					}, function(error) {
						alert(error);
					});
				} else {
					request.post("cancelRelating.action", {
						handleAs : "json",
						data : {roleId : _roleId}
					}).then(function(response) {
						
					}, function(error) {
						alert(error);
					});					
				}
			}
		});

		setTimeout(function() {
			setTimeout(function() {
				fx.fadeOut({
					node : "loader",
					duration : 300,
					onEnd : function(n) {
						n.style.display = "none";
					}
				}).play();
			}, 100);
		}, 200);
	});
});